
//Init Float DateTime Picker
const date = new Date()
const initYear = 2017;
const years = []
const months = []
const days = []
const hours = []
const minutes = []
var thisMon = date.getMonth();
var thisDay = date.getDate();

initTimePicker();

// pages/trade/trade.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
  //Data
    //CarList data for wx:for
    carArray: "",
    userID:"",
    // carListIndex:"",
    currentTakenTableIndex:"",

    orderArray:[
      // { name: 'Agt', startTime: '2018-07-19 15:00', endTime: '2018-07-19 16:00' },
      // { name: 'Lara', startTime: '2018-07-20 13:00', endTime: '2018-07-21 17:00' }
    ],

    serverUrl: {
      getAll: getApp().globalData.serverUrlPrefix+'/CarRental/CarList/ShowAll',
      order: getApp().globalData.serverUrlPrefix+'/CarRental/Order/Add',
      previewTakenTable: getApp().globalData.serverUrlPrefix+'/CarRental/Order/ShowTakenTable'
    },
  
  ///Float Window
    //Size & state
    itemHeight: "60rpx",
    floatWindowShow: false,//only be true when debug
    orderIndex:-1,
    isFloatUpScrollViewShow: false,
    floatWindowSize: ["60%", "20%"],//[Height,Top]
    baseAreaSize: ["15%", "85%"], //[upArea,downArea]
    upAreaSize: ["50%", "50%", "0%"],
    //DateTime Picker
    years: years,
    year: date.getFullYear(),
    months: months,
    month: thisMon,
    days: days,
    day: thisDay,
    value: [1, thisMon - 1, thisDay - 1, 0, 0],
    hours: hours,
    hour: "00",
    minutes: minutes,
    minute: "00",
    //PickerTime
    pickerTimeStyleStart:"floatDateTimePickerText_Selected",
    pickerTimeStyleEnd: "floatDateTimePickerText",
    //Start
    yearStart: date.getFullYear(),
    monthStart: thisMon,
    dayStart: thisDay,
    hourStart: "00",
    minuteStart: "00",
    //End
    yearEnd: date.getFullYear(),
    monthEnd: thisMon,
    dayEnd: thisDay,
    hourEnd: "00",
    minuteEnd: "00",
    //Focus on the 'Start' time picker first
    pickerTimeFlag : "start",
    //可预约时间
    availableTime: "2018-07-19 15:00 ~ 2018-07-25 15:07",//Test info
    //Picked Time
    startStr:'',
    endTime:'',
    
//Background Pictures
    //Title Swiper
    imgUrls: [
      '../../pics/car1.jpg',
      '../../pics/car2.jpg',
      '../../pics/car3.jpg'
    ],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000




  },

  changeFloatWindowStyle:function(isExpand){
      console.log("Changing now  "+isExpand);
      if(isExpand == true){
        this.setData(
          {
            isFloatUpScrollViewShow: true,
            floatWindowSize: ["80%", "10%"],//[Height,Top]
            baseAreaSize: ["45%", "55%"], //[upArea,downArea]
            upAreaSize: ["12%", "13%", "75%"],
          }
        )
      }else{
        this.setData(
          {
            isFloatUpScrollViewShow: false,
            floatWindowSize: ["60%", "20%"],//[Height,Top]
            baseAreaSize: ["15%", "85%"], //[upArea,downArea]
            upAreaSize: ["50%", "50%", "0%"],
          }
        )
      }
      

  },


  //Called when TimePicker changed
  bindPickerViewChange: function (e) {
    // console.log("PickerTime changed");

    console.log(this.data.hours)

    const val = e.detail.value
    console.log(val);
    this.setData({
      year: this.data.years[val[0]],
      month: this.data.months[val[1]],
      day: this.data.days[val[2]],
      hour: this.data.hours[val[3]],
      minute: this.data.minutes[val[4]],
    })
    
    this.updateDaysWhenChanged();
    
    this.updateStartEndTime();

    this.getCurrentOrderString();
  },

  //Confirm an order
  confirmOrder:function(e){
      this.requestToOrder();
  },

  //update the start/end time of the confirm order
  getCurrentOrderString:function(){
    this.data.startStr = this.data.yearStart + "-" + this.data.monthStart + "-" + this.data.dayStart 
      + " " + this.data.hourStart +":"+ this.data.minuteStart;
    this.data.endStr = this.data.yearEnd + "-" + this.data.monthEnd + "-" + this.data.dayEnd
                     + " " + this.data.hourEnd + ":" + this.data.minuteEnd;
    console.log("Start:" + this.data.startStr);
    console.log("End:" + this.data.endStr);
  },

  //update the days
  updateDaysWhenChanged:function(){
    
    var totalDay = mGetDate(this.data.year, this.data.month);
    var changeDate = [];
    for (let i = 1; i <= totalDay; i++) {
      var k = i;
      if (0 <= i && i < 10) {
        k = "0" + i
      }
      changeDate.push(k)
    }
    this.setData({
      days: changeDate
    })
  },

  //Using raw data update the 'start'/'end' time picker
  updateStartEndTime: function () {
    if (this.data.pickerTimeFlag == "start"){
      this.setData({
        yearStart: this.data.year,
        monthStart: this.data.month,
        dayStart: this.data.day,
        hourStart: this.data.hour,
        minuteStart: this.data.minute,
      })
    }
    else if (this.data.pickerTimeFlag == "end") {
      this.setData({
        yearEnd: this.data.year,
        monthEnd: this.data.month,
        dayEnd: this.data.day,
        hourEnd: this.data.hour,
        minuteEnd: this.data.minute,
      })
    }
    
  },

  //Set the Time Picker to the date
  updateTimePickerByDate: function (baseTime) {
    var date = new Date(baseTime);
    var curYear = date.getFullYear() - initYear;
    var curMonth = date.getMonth();
    var curDate = date.getDate() - 1;
    var curHour = date.getHours();
    var curMinutes = date.getMinutes();
    this.setData(
      {
        value: [curYear, curMonth, curDate, curHour, curMinutes],
      }
    )

  },

  //Order Button in the front
  orderButtonClicked:function(e)
  {
    var index = e.currentTarget.id;
    this.data.orderIndex = index;
    // console.log(index);
    var value = this.data.carArray[index];
    console.log(value);
    
    this.getCurrentOrderString();

    var takenTableShow = false;
    console.log(value.status);
    if (value.status != 0)
    {
      takenTableShow = true;
    }
    this.changeFloatWindowStyle(takenTableShow);

 
    this.data.currentTakenTableIndex = value.id;
    this.requestTakenTable(value.id);


    this.setData(
      {
        floatWindowShow: true,
        availableTime: value.startTime + " ~ " + value.endTime,

      }
    )


  },

  //The button on the TimePicker Window
  floatPickerTimeButtonClicked:function(e){
    var id = e.currentTarget.id;
    if (this.data.pickerTimeFlag == id)
      return false;

    this.data.pickerTimeFlag = id;
    //Swap the two picker time item to change style
    var temp = this.data.pickerTimeStyleStart;
    this.setData(
      {
        pickerTimeStyleStart: this.data.pickerTimeStyleEnd,
        pickerTimeStyleEnd: temp
      }
    )
    // this.getCurrentOrderString();
    if(id  == "start")
    {
      console.log("startTime " + this.data.startStr);
      this.updateTimePickerByDate(this.data.startStr);
    }
    else if(id == "end")
    {
      console.log("endTime " + this.data.endStr);
      this.updateTimePickerByDate(this.data.endStr);
    }
  },

///Network
  //Get CarList info
  requestAllOrders:function()
  {
    console.log("Requesting all carList");
    var self = this;
    wx:wx.request({
      url: this.data.serverUrl.getAll, //Show all Orders
      data: {
        // Unuse Data 
      },
      header: {
        'content-type': 'application/json;' // 默认值
      },
      success: function(res) {
        // console.log(self);
        console.log("Receive data from server");
        // console.log(res.data);
        self.parseServerData(res.data);
      },
      fail: function(res) {
        self.showMessage('网络错误');
      },
      complete: function(res) {}
    })
  },
  //Request to Order
  requestToOrder: function () {
    console.log("Requesting To Order" + "ST:" + this.data.startStr + " Ed:" + this.data.endStr);
    var self = this;
    wx: wx.request({
      url: this.data.serverUrl.order, //Show all Orders
      data: {
        carListID: self.data.carArray[self.data.orderIndex].id,
        customerID: this.data.userID,
        startTime: self.data.startStr,
        endTime: self.data.endStr,
        baseStartTime: self.data.carArray[self.data.orderIndex].startTime,
        baseEndTime: self.data.carArray[self.data.orderIndex].endTime,
        statusStr: '0'
      },
      header: {
        'content-type': 'application/json;' // 默认值
      },
      success: function (res) {
        // console.log("1:"+res)
        // console.log('RequestToOrder:'+res.data);
        // self.showMessage(res.data);
        // self.showMessage('预约成功');
        if(res.data == 1){
          self.showMessage('预约成功');
          self.setData(
            {
              // floatWindowShow:false
            }
          )
          self.requestAllOrders();
          self.requestTakenTable(self.data.currentTakenTableIndex);

        }else{
          self.showMessage(res.data);
        }
        
      },
      fail: function (res) {
        self.showMessage('网络错误');
      }
    })
  },
  //Request Preview TakenTable
  requestTakenTable: function (carListID) {
    console.log("Requesting TakenTable for " + carListID);
    var self = this;
    wx: wx.request({
      url: this.data.serverUrl.previewTakenTable, 
      data: {
        carListID: carListID,
      },
      header: {
        'content-type': 'application/json;' // 默认值
      },
      success: function (res) {

        console.log(res.data);
        self.parseCarListOrderData(res.data);
      },
      fail: function (res) {
        self.showMessage('网络错误');
      }
    })
  },

  //Parsing carList data from Server
  parseServerData: function (data)
  { 
    console.log("Data Size:"+data.length);
    this.setData(
      {
        carArray:data
      }
    )
  },
  parseCarListOrderData:function(data){
    this.setData(
      {
        orderArray: data
      }
    )
  },

  //Just hide the Float Window when cancel
  cancelButtonClicked: function(e) {
    // console.log(e);
    this.setData(
      {
        floatWindowShow: false
      }
    )
    // this.changeFloatWindowStyle(true);
    // this.updateTimePickerByDate("2020-01-01 18:20");
  },

  

  showMessage: function (message){
    console.log('Message:'+message);
    wx:wx.showToast({
      title: message,
      icon: 'none',
      duration: 3000,
    })
  },


///Scroll View Handler
  upper: function (e) {
    // console.log(e)
  },
  lower: function (e) {
    // console.log(e)
  },

///Page
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var userID = getApp().globalData.userID;
    console.log("Userid:"+userID);
    this.data.userID = userID;

    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
   
    this.requestAllOrders();

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

///Init the Float Time Pickers
function mGetDate(year, month) {
  var d = new Date(year, month, 0);
  return d.getDate();
}
function initTimePicker() {
  //Add years
  for (let i = initYear; i <= date.getFullYear() + 2; i++) {
    years.push(i)
  }
  //Add month
  for (let i = 0; i <= 11; i++) {
    var k = i;
    if (0 <= i && i < 9) {
      k = "0" + (i + 1);
    } else {
      k = (i + 1);
    }
    months.push(k)
  }
  if (0 <= thisMon && thisMon < 9) {
    thisMon = "0" + (thisMon + 1);
  } else {
    thisMon = (thisMon + 1);
  }
  if (0 <= thisDay && thisDay < 10) {
    thisDay = "0" + thisDay;
  }
  //Add days
  var totalDay = mGetDate(date.getFullYear(), thisMon);
  for (let i = 1; i <= 31; i++) {
    var k = i;
    if (0 <= i && i < 10) {
      k = "0" + i
    }
    days.push(k)
  }

  for (let i = 0; i <= 23; i++) {
    var k = i;
    if (0 <= i && i < 10) {
      k = "0" + i
    }
    hours.push(k)
  }
  for (let i = 0; i <= 59; i++) {
    var k = i;
    if (0 <= i && i < 10) {
      k = "0" + i
    }
    minutes.push(k)
  }
}